<?php

namespace App\Http\Controllers\SiteAce;
use App\Services\OSS;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use App\Http\Controllers\Controller;
use App\bills;
use App\Services\SignatureHelper;
class Store extends Controller
{
    use \App\Traits\ApiTrait, \App\Traits\SessionTrait, \App\Traits\AjaxTrait, \App\Traits\DbTrait, \App\Traits\UserTrait;
    public $curl;
    private $_requestData;
    public $accessKeyId="LTAIGiLtgVlZQt7y";
    public $accessKeySecret="9Br1cyuEPxoXZ7gS66cgWs4ELViAsq";
    public function __construct(Request $request)
    {
        $this->_requestData = $request->all();
        $this->curl = new \Ixudra\Curl\CurlService();
    }
    public function formatDataBody($data,$status=1,$msg=''){
        $resultData=[
          'status'=>$status,
          'msg'=>$msg,
          'data'=>$data,
        ];
        return json_encode($resultData);
    }
    //登录
    public function login(Request $request){
      $userPhone=$request->userPhone;
      $code=$request->code;
      $time=time();
      $verifyCode=DB::table('sms_code_log')->whereRaw('phone = ? and code= ?',[$userPhone,$code])->orderby('id','desc')->first();
      // var_dump($time-$verifyCode->create_time);
      if($userPhone=='17000000001' && $code=='123456'){
        $data=DB::table('user')->where(['userPhone'=>$userPhone])->first();
        return response($this->formatDataBody($data));
      }elseif ($userPhone=='17000000001' && $code!='123456') {
        return response($this->formatDataBody(false,202,'验证码不正确或已过期'));
      }
      DB::beginTransaction();
      try {
        // if($verifyCode!==null && $verifyCode->code==$code){
        if($verifyCode!==null && $verifyCode->code==$code && $time-$verifyCode->create_time<=900){
            // DB::beginTransaction();
            $token=MD5($time);
            $bool=DB::update('update user set userToken= ? where userPhone= ? ',[$token,$userPhone]);
            if($bool){
              $data=DB::table('user')->where(['userPhone'=>$userPhone])->first();
              DB::commit();
              return response($this->formatDataBody($data));
            }
            else{
              $newUser=DB::table('user')->insert(['userPhone'=>$userPhone,'userName'=>$userPhone,'createTime'=>$time,'userToken'=>$token]);
              DB::commit();
              if($newUser){
                $data=DB::table('user')->where(['userPhone'=>$userPhone])->first();
                // var_dump('1');
                return response($this->formatDataBody($data));
              }
              else{
                DB::rollback();
                return response($this->formatDataBody(false,204,'登录失败'));
              }

            }
        }
        else{
          DB::rollback();
          return response($this->formatDataBody(false,202,'验证码不正确或已过期'));
        }
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(false,901,$e));
      }
    }
    //轮播图
    public function picList(Request $request){
      // $billNumber = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
      // var_dump($billNumber);
      $DBData=DB::table('app_pic_list')->orderby('id','desc')->offset(0)->limit(3)->get();
      return response($this->formatDataBody($DBData));
    }
    //首页内容
    public function indexSkuList(Request $request){
      $DBData=DB::table('sku')->orderby('skuId','desc')->offset(0)->limit(6)->get();
      return response($this->formatDataBody($DBData));
    }
    //分类内容
    public function getSkuByCategory(Request $request){
      $categoryId=$request->categoryId;
      $pageNum=$request->pageNum;
      if($pageNum==null||!isset($pageNum)){
        $pageNum=0;
      }
      if($categoryId==null||$categoryId==0){
        return response($this->formatDataBody(false,0,'未获取到分类信息'));
      }
      $DBData=DB::table('sku')->where('categoryId',$categoryId)->orderby('skuId','desc')->offset($pageNum*6)->limit(6)->get();
      return response($this->formatDataBody($DBData));
    }
    //分类信息
    public function getCategory(Request $request){
      $DBData=DB::table('category')->orderby('categoryId','desc')->get();
      return response($this->formatDataBody($DBData));
    }
    //获取sku详情
    public function getSkuDetail(Request $request){
      $skuId=$request->skuId;
      $data=DB::table('sku')->where(['skuId'=>$skuId])->first();
      return response($this->formatDataBody($data));
    }
    //创建订单
    public function createBill(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $billAmount=$request->billAmount;
      $billAddress=$request->billAddress;
      $billContractor=$request->billContractor;
      $billPhone=$request->billPhone;
      $time=time();
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      DB::beginTransaction();
      try {
        $billData=$request->billData;
        $listData=json_decode($billData,true);
        // var_dump($listData);
        if(count($listData)>0)
        // if(1==1)
        {
          $billNumber = date('Ymd').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
          $bill = bills::insertGetId(['billList' => $billData,'userId'=>$userId ,'createTime'=>$time ,'billAmount'=>$billAmount ,'billAddress'=>$billAddress ,'billContractor'=>$billContractor ,'billPhone'=>$billPhone,'billNumber'=>$billNumber]);
          $newId=$bill;
          foreach ($listData as $key => $value) {
            $arrInsert[$key]=$value;
            $arrInsert[$key]['billId']=$newId;
            // $arrInsert[$key]['skuId']=$value['skuId'];
            // $arrInsert[$key]['skuAmount']=$value['skuAmount'];
            // $arrInsert[$key]['skuPrice']=$value['skuPrice'];
            // $arrInsert[$key]['skuUnit']=$value['skuUnit'];
            // $arrInsert[$key]['skuImg']=$value['skuImg'];
            // $arrInsert[$key]['skuName']=$value['skuName'];
            $arrInsert[$key]['createTime']=$time;
          }
          // var_dump($arrInsert);
          $bool=DB::table('billSkuRelation')->insert($arrInsert);
          // var_dump($bool);
          DB::commit();
          return response($this->formatDataBody(['billId'=>$newId]));
        }else{
          DB::rollback();
          return response($this->formatDataBody(false,0,'请勿提交空订单'));
        }
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(false,0,$e));
      }
    }
    //获取历史订单
    public function getBillList(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $pageNum=$request->pageNum;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      if($pageNum==null||!isset($pageNum)){
        $pageNum=0;
      }
      $DBData=DB::table('bills')->where('userId',$userId)->orderby('billId','desc')->offset($pageNum*6)->limit(6)->get();
      if(count($DBData)>0){
        foreach ($DBData as $key => $value) {
          $value->billList=json_decode($value->billList);
        }
      }
      return response($this->formatDataBody($DBData));
    }
    //获取地址列表
    public function addressList(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      $DBData=DB::table('address')->where(['userId'=>$userId])->orderby('addressId','desc')->get();
      // $DBData=json_encode($DBData);
      return response($this->formatDataBody($DBData));
    }
    //创建地址
    public function createAddress(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $data['userId']=$userId;
      $data['contractName']=$request->contractName;
      $data['contractPhone']=$request->contractPhone;
      $data['province']=$request->province;
      $data['city']=$request->city;
      $data['district']=$request->district;
      $data['addressDetail']=$request->addressDetail;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      DB::beginTransaction();
      try {
        $bool=DB::table('address')->insert($data);
        DB::commit();
        return response($this->formatDataBody($bool));
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(false,207,$e));
      }
    }
    //修改昵称
    public function editUserName(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $userName=$request->userName;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      DB::beginTransaction();
      try {
        $bool= DB::table('user')->where('userId', $userId)->update(['userName'=>$userName]);
        DB::commit();
        if($bool) return response($this->formatDataBody($bool));
        else return response($this->formatDataBody(false,208,'修改失败，请重试'));
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(false,207,$e));
      }
    }
    //获取昵称
    public function getUserName(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      $data=DB::table('user')->where(['userId'=>$userId])->first();
      $DBData=['userName'=>$data->userName];
      return response($this->formatDataBody($DBData));
    }
    //获取实名状态
    public function getRealNameState(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      $data=DB::table('user')->where(['userId'=>$userId])->first();
      $DBData=['realNameState'=>$data->realNameState];
      return response($this->formatDataBody($DBData));
    }
    //实名认证提交
    public function editRealNameState(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $data['userId']=$userId;
      $data['realName']=$request->realName;
      $data['IDNumber']=$request->IDNumber;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      DB::beginTransaction();
      try {
        $bool=DB::table('realName')->insert($data);
        if($bool){
          $result=DB::table('user')->where(['userId'=>$userId])->update(['realNameState'=>1]);
        }
        DB::commit();
        if($result) return response($this->formatDataBody($result));
        else return response($this->formatDataBody(false,208,'提交失败'));
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(false,207,$e));
      }
    }
    //修改绑定手机
    public function editUserPhone(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      // $data['userId']=$userId;
      $data['oldPhone']=$request->oldPhone;
      $data['oldCode']=$request->oldCode;
      $data['newPhone']=$request->newPhone;
      $data['newCode']=$request->newCode;
      $time=time();
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      $verifyNewPhone=DB::table('user')->where(['userPhone'=>$data['newPhone']])->first();
      if($verifyNewPhone!=null && isset($verifyNewPhone->userId)) return response($this->formatDataBody(false,901,'新的手机号已注册'));
      $verifyCodeOld=DB::table('sms_code_log')->whereRaw('phone = ? and code= ?',[$data['oldPhone'],$data['oldCode']])->orderby('id','desc')->first();
      $verifyCodeNew=DB::table('sms_code_log')->whereRaw('phone = ? and code= ?',[$data['newPhone'],$data['newCode']])->orderby('id','desc')->first();
      if($verifyCodeOld!==null && $time-$verifyCodeOld->create_time<=900 && $verifyCodeNew!==null && $time-$verifyCodeNew->create_time<=900){
        DB::beginTransaction();
        try {
            $result=DB::table('user')->where(['userId'=>$userId])->update(['userPhone'=>$data['newPhone']]);
            DB::commit();
            if($result) return response($this->formatDataBody($result));
            else return response($this->formatDataBody(false,208,'修改失败'));
        } catch (\Exception $e) {
          DB::rollback();
          return response($this->formatDataBody(false,207,$e));
        }
      }else {
        return response($this->formatDataBody(false,202,'验证码不正确或已过期'));
      }
    }
    //修改地址
    public function editAddress(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $addressId=$request->addressId;
      $data['userId']=$userId;
      $data['contractName']=$request->contractName;
      $data['contractPhone']=$request->contractPhone;
      $data['province']=$request->province;
      $data['city']=$request->city;
      $data['district']=$request->district;
      $data['addressDetail']=$request->addressDetail;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      DB::beginTransaction();
      try {
        $bool= DB::table('address')->where('addressId', $addressId)->update($data);
        DB::commit();
        if($bool) return response($this->formatDataBody($bool));
        else return response($this->formatDataBody(false,208,'地址修改失败，请重试'));
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(false,207,$e));
      }
    }
    //获取验证码
    public function getCode(Request $request){
      $userPhone=$request->userPhone;
      $code = mt_rand(100000, 999999);
      $type=$request->type;
      // if($type==null || $type==0)$msgModelCode='SMS_133225048';
      if($type==null || $type==0)$msgModelCode='SMS_137422571';
      else $msgModelCode='SMS_137422571';
      $time=time();
      try {
        $result = $this->sendSms($userPhone,"阿里云短信测试专用",$msgModelCode,$code);
        DB::table('sms_code_log')->insert(['phone'=>$userPhone,'code'=>$code,'create_time'=>$time,'type'=>'1','from'=>'aliyun']);
        return response($this->formatDataBody($result));
      } catch (\Exception $e) {
        return response($this->formatDataBody($e,201,'发送失败，请重试'));
      }
    }
    /**
     * 阿里云通道发送短信
     */
    function sendSms($userPhone,$signName,$templateCode,$code) {

        $params = array ();

        // *** 需用户填写部分 ***

        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
        $accessKeyId = $this->accessKeyId;
        $accessKeySecret = $this->accessKeySecret;

        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = $userPhone;

        // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = $signName;

        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = $templateCode;

        // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        $params['TemplateParam'] = Array (
            "code" => $code
        );

        // fixme 可选: 设置发送短信流水号
        // $params['OutId'] = "12345";

        // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
        // $params['SmsUpExtendCode'] = "1234567";


        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
        // var_dump($params);

        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new SignatureHelper();

        // 此处可能会抛出异常，注意catch
        $content = $helper->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            ))
            // fixme 选填: 启用https
            // ,true
        );

        return $content;
    }

    public function getAppVersion(request $request){
      $state=0;
      $DBData=DB::table('app_ver')->orderby('id','desc')->first();
      $ver=$DBData->ver;
      $url=$DBData->url;
      $oldver=$request->ver;
      if($ver>$oldver)$state=1;
      $result=[
        'ver' => $ver,
        'url' => $url,
        'state'=>$state
    ];
      return json_encode($result);
    }
    public function updateAppVersion(request $request){
        // Start transaction!
        DB::beginTransaction();
        try {
          $ver=$request->ver;
          $url=$request->url;
          DB::insert("insert into app_ver (ver,url) values ('$ver','$url')");
          $status=1;
        }
        catch(\Exception $e)
        {
            DB::rollback();
            $status=0;
        }
        DB::commit();
        return json_encode(['status'=>$status]);
    }
    /**
     * 文件上传
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function uploadFile(Request $request)
    {
        $file = $request->file('files');
        $fileExtension = $file->getClientOriginalExtension();
        $fileOriginalName = $file->getClientOriginalName();
        list($time1, $time2) = explode(' ', microtime());
        $microTime = (float) $time2 + (float) $time1;
        $newName = $microTime . "." . $fileExtension;
        $ossConfigData = config('oss.' . config('oss.default'));
        if (in_array($fileExtension, $ossConfigData['img_ext'])) {
            $bucketName = $ossConfigData['image_bucket'];
        } else {
            $bucketName = $ossConfigData['file_bucket'];
        }
        //先放到服务器，再上传到OSS
        $localPath = public_path() . '/uploads';
        $file->move($localPath, $newName);

        $ossPath = 'tmpfile/' . $newName;

        $result = OSS::publicUpload($bucketName, $ossPath, $localPath . '/' . $newName);
        $ossUrl = OSS::getPublicUploadUrl($bucketName, $ossPath);

        if ($result) {
            echo json_encode(['name' => $fileOriginalName, 'url' => $ossUrl]);
        } else {
            echo json_encode(['result' => 999, 'msg' => '上传错误']);
        }
    }

    /**
     * 发送短信验证码
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function pushCode(Request $request)
    {
        $postData = $this->ajaxSendSms($request);
        $postData['code'] = mt_rand(100000, 999999);
        $code=$postData['code'];
        $postData['ip'] = $request->ip();
        $postData['type'] = 1;
        $result = $this->dbAddSmsCodeLog($postData);
        if ($result['result'] == 0) {
            if (env('DB_CONNECTION') == 'product_mysql') {
                $result2 = $this->pushCodeTrait(parent::CODE_SEND_SMS, $postData);
                $result['code']=$code;
            } else {
                $result2 = true;
                $result['code']=$code;
            }
            $result = $result2 ? $result : ['result' => -1, 'msg' => '短信发送失败，请重试'];
        }
        echo json_encode($result);
    }

    /**
     * 邮箱认证
     * @return [type] [description]
     */
    public function emailAuth()
    {
        $data = ['md5' => $this->_requestData['flag'], 'email' => $this->_requestData['source']];
        $tableData = $this->validateEmailFlag($data);
        if (!$tableData['id']) {
            $viewData = ['seo' => $this->returnSeoInfo('tanwin_index'), 'validate_result' => false];
            return view('web.company.email_auth_result', $viewData);
        }
        $this->validateEmailFlagSuccess($tableData);

        $userInfo = [
            'account_phone' => $tableData['phone'],
            'new_pwd' => mt_rand(10000000, 99999999) . 'abc',
        ];
        $this->userForgetPwdTrait(parent::CODE_UPDATE_USER_PWD, $userInfo);

        $mailInfo = [
            'mail_address' => $tableData['email'],
            'mail_subject' => '碳银网帐号信息' . time(),
            'mail_content' => '您登录碳银网的密码为:' . $userInfo['new_pwd'],
        ];
        $this->pushEmailData(parent::CODE_SEND_EMAIL, $mailInfo);
        $viewData = ['seo' => $this->returnSeoInfo('tanwin_index'), 'validate_result' => true];
        return view('web.company.email_auth_result', $viewData);
    }
}
